function varargout = TLExtractBitsDlg(action, varargin)

% TL_EXTRACTBITS_DLG manages the user interface for TargetLink Extract Bits block
%
% SYNTAX dlgInfo = TLExtractbitsDlg('GetDlgInfo');
%   gets dialog info of TargetLink Extract Bits block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLExtractbitsDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLExtractbitsDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLExtractbitsDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLExtractbitsDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLExtractbitsDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLExtractbitsDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.8 $
% $Date: 2011/03/17 11:53:58MEZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


% switch-case block for possible actions
switch lower(action)
    case 'getdlginfo'
        [varargout{1:2}] = FcnGetDlgInfo(varargin{1});
    case 'ctrlpositions'
        [varargout{1:2}] = FcnCtrlPositions(varargin{:});
    case 'create'
        [varargout{1}]   = FcnCreate(varargin{:});
    case 'manage'
        [varargout{1:2}] = FcnManage(varargin{:});
    case 'managesystemicons',
        [varargout{1:2}] = FcnManageSystemIcons(varargin{:});
    case 'update'
        [varargout{1}]   = FcnUpdate(varargin{:});
    case 'apply'
        [varargout{1:2}] = FcnApply(varargin{:});
    otherwise
        error(['Invalid action "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile, blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile, blockstr);
        end

    case 'ViewCode'
        tl_create_links_to_model('ShowComputation', dlgdata.model, 'output');

    otherwise
        error('Invalid callback');

end % switch(action)


%--------------------------------------------------------------------------
% FcnGetDlgInfo gets dialog info of TargetLink bitset block
%
% INPUT ARGUMENTS
%   hBlock      current block handle
%
% OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%   tlData      TargetLink block data
%--------------------------------------------------------------------------
function [dlgInfo, tlData] = FcnGetDlgInfo(hBlock)

dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Extract Bits';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
dlgInfo.pageNames = { ...
    'Output', ...
    'Logging', ...
    'Documentation'};
tlData = get_tlcg_data(hBlock);


%--------------------------------------------------------------------------
% FcnCtrlPositions calculates the cotrol positions of all controls of
% dialog page: <pageName>
%
% INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometrie data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%   bCodeComment    should code comment be available
%   dlgdata         dialog data
%
% OUTPUT ARGUMENTS
%   sheetDims   modified dimension of sheet
%   ctrlPos     positions of controls
%--------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCtrlPositions(pageName, commonGeom, dlgInfo, sheetDims)  %#ok<INUSL>
% initialize output parameter                                
ctrlPos = [];                         
switch pageName
    case 'Output'
        [sheetDims, ctrlPos] = FcnCalcOutputControlPositions(commonGeom);
    case 'Logging'
        % calculate positions of logging controls
        excludedCtrls = {'autoscaling'};    
        [sheetDims, ctrlPos] = TLManageLoggingCtrls('calcCtrls', ...
                                        commonGeom, sheetDims, excludedCtrls);
    case 'Documentation'
        bTblBlock = 0;
        bCodeComment = 1;
        [sheetDims, ctrlPos] = TLManageDocCtrls('ctrlpos', commonGeom, ...
                                       sheetDims, bCodeComment, bTblBlock);
end


%--------------------------------------------------------------------------
% FcnCreate creates all controls of dialog page: <pageName>
%
% INPUT ARGUMENTS
%   pageName    name of current page
%   dlgfig      current figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnCreate(pageName, dlgfig, dlgdata)
pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
switch pageName
    case 'Output'
        dlgdata = FcnCreateOutputControls(pageNum, dlgfig, dlgdata);
    case 'Logging'
        dlgdata = TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata);
    case 'Documentation'
        dlgdata = TLManageDocCtrls( ...
            'create', pageNum, dlgfig, dlgdata);
end
% ctrlPos are not needed anymore
dlgdata.pageData{pageNum}.ctrlPos = [];


%--------------------------------------------------------------------------
% FcnManage manage all actions of dialog page: <pageName>
%
% INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          name of current page
%   dlgdata         dialog data
%   pageAction      name of calling control
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%   bModified   flag = 1, if dialog data are modified, = 0 otherwise
%--------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManage(pageName, dlgfig, dlgdata, pageAction)
bModified = false;
pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
switch pageName
    case 'Output'
        [dlgdata, bModified] = FcnManageOutputControls(pageNum, dlgfig, ...
            dlgdata,pageAction);
    case 'Logging'
        [dlgdata, bModified] = TLManageLoggingCtrls('manage', pageNum, dlgdata, ...
                pageAction, 'logdata');
    case 'Documentation'
         [dlgdata, bModified] = TLManageDocCtrls('callback', ...
                                        pageNum, dlgfig, dlgdata, pageAction);
end

%--------------------------------------------------------------------------
% FcnUpdate updates all controls of dialog page: <pageNum>
%
% INPUT ARGUMENTS
%   dlgfig          name of current page
%   dlgdata         dialog data
%   pagenum         number of current tab
%
% OUTPUT ARGUMENTS
%   dlgdata         dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdate(dlgfig, dlgdata, pageNum)
pageName  = dlgdata.pageNames{pageNum};
switch pageName
    case 'Output'
        dlgdata = FcnUpdateOutputControls(dlgfig, dlgdata, pageNum);
    case 'Logging'
        dlgdata =   TLManageLoggingCtrls('update', pageNum, dlgdata, 'logdata', 'output');
        TLManageLoggingCtrls('setCtrls', pageNum, dlgfig, dlgdata);
    case 'Documentation'
        TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
end


%--------------------------------------------------------------------------
% FcnApply writes current blockdata to block and DD
%
% INPUT ARGUMENTS
%   -/-
%
% OUTPUT ARGUMENTS
%   argout      return value is bContinue
%--------------------------------------------------------------------------
function [dlgdata, bClose] = FcnApply(dlgfig, dlgdata, bClose) %#ok<INUSL>
[dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);

%-----------------------------------------------------------------------------------------
% FcnCalcOutputControlPositions calculates positions for all controls on output page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims,ctrlPos] = FcnCalcOutputControlPositions(commonGeom)

% calculate positions of output controls
excludedCtrls = {'saturate', 'inheritproperties'};
[sheetDims, ctrlPos, colOutputFrame, colDelta, rowDelta] =  ...
                        tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = {...
    'Bits to extract',      'text'; ...
    'Number of bits',       'text'; ...
    'Bit range',            'text'; ...
    '123',                  'edit'; ...
    '+',                    'pushbutton'; ...
    'Range starting with most significant bit', 'popupmenu'; ...
    'Range ending with least significant bit',  'popupmenu'};
[bitstoextractLabelSize, ...
    numOfBitsLabelSize, ...
    bitidxrangeLabelSize, ...
    numOfBitsEditSize, ...
    numOfBitsButtonSize, ...
    bitToExtractPopupSize1, ...
    bitToExtractPopupSize2] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

% get element with highest width of bitToExtractPopup
if bitToExtractPopupSize1(1) > bitToExtractPopupSize2(1)
    bitToExtractPopupSize = bitToExtractPopupSize1;
else
    bitToExtractPopupSize = bitToExtractPopupSize2;
end

% save groupbox start position
cxGroupbox = ctrlPos.tlcgoptGroupbox(1);

% get maximum of bitstoextractLabelSize and width of first column
if colOutputFrame(2) - colOutputFrame(1) < bitstoextractLabelSize(1) + colDelta/3
    corr = bitstoextractLabelSize(1) + colDelta/3 - (colOutputFrame(2) - colOutputFrame(1));
    colOutputFrame(2:end) = colOutputFrame(2:end) + corr;
    % move all controls except the first column before calculate bit extraction control positions
    ctrlNames = fieldnames(ctrlPos);
    ctrlNames = reshape(ctrlNames, 1, length(ctrlNames));
    for k = 1 : length(ctrlNames)
        if eval(['ctrlPos.',ctrlNames{k},'(1)']) > colOutputFrame(1)
            eval(['ctrlPos.',ctrlNames{k},'(1) = ctrlPos.',ctrlNames{k},'(1) + corr;']);
        end
    end
    % adapt groupBoxes
    ctrlPos.tlcgoptGroupbox(3) = ctrlPos.tlcgoptGroupbox(3) + corr;
end

% define an additional box for bit extraction
ctrlPos.tlcgoptGroupbox(1) = cxGroupbox;
ctrlPos.parametersGroupbox(1) = ctrlPos.tlcgoptGroupbox(1);
ctrlPos.parametersGroupbox(2) = ctrlPos.tlcgoptGroupbox(2) + ...
    ctrlPos.tlcgoptGroupbox(4) + commonGeom.textHeight;
ctrlPos.parametersGroupbox(3) = ctrlPos.tlcgoptGroupbox(3);
ctrlPos.parametersGroupbox(4) = commonGeom.popupHeight + ...
    commonGeom.frameTopEdgeBuffer + commonGeom.frameBottomEdgeBuffer;

% bitstoextractLabel
cx = colOutputFrame(1);
cy = commonGeom.frameBottomEdgeBuffer;
ctrlPos.bitstoextractLabel = [cx cy bitstoextractLabelSize];

% bitstoextractPopup
cx = colOutputFrame(2);
ctrlPos.bitstoextractPopup = [cx cy bitToExtractPopupSize];

% numOfBitsLabel
cx = ctrlPos.bitstoextractPopup(1) + ctrlPos.bitstoextractPopup(3) + colDelta + colDelta/2;
ctrlPos.numOfBitsLabel = [cx cy numOfBitsLabelSize];
% numOfBitsEdit
cx = ctrlPos.numOfBitsLabel(1) + ctrlPos.numOfBitsLabel(3) + colDelta/3;
ctrlPos.numOfBitsEdit = [cx cy numOfBitsEditSize];
% numOfBitsEditButtonDown
numOfBitsButtonSize = numOfBitsButtonSize .* [1 0.5];
cx = ctrlPos.numOfBitsEdit(1) + ctrlPos.numOfBitsEdit(3) + colDelta/5;
ctrlPos.numOfBitsEditButtonDown = [cx cy numOfBitsButtonSize];
% numOfBitsEditButtonUp
cyTmp = cy + commonGeom.editHeight/2;
ctrlPos.numOfBitsEditButtonUp = [cx cyTmp numOfBitsButtonSize];

% bitidxrangeLabel
cx = colOutputFrame(7) - colDelta/3 - bitidxrangeLabelSize(1);
ctrlPos.bitidxrangeLabel = [cx cy bitidxrangeLabelSize];

% bitidxrangeEdit
cx = colOutputFrame(7);
ctrlPos.bitidxrangeEdit = [cx cy ctrlPos.unitEdit(3) ctrlPos.unitEdit(4)];

% calculate sheet Dimensions
width = ctrlPos.tlcgoptGroupbox(3) ...
    + 2 * commonGeom.frameSideEdgeBuffer;
height = ctrlPos.tlcgoptGroupbox(4) ...
    + ctrlPos.parametersGroupbox(4) ...
    + 2 * commonGeom.textHeight ...
    + commonGeom.sheetBottomEdgeBuffer;

sheetDims = [width height];


%-----------------------------------------------------------------------------------------
% FcnCreateOutputControls creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateOutputControls(pageNum,dlgfig,dlgdata)

% create logging controls
dlgdata = TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata);

Children = dlgdata.pageData{pageNum}.children;
ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
pageName = dlgdata.pageNames{pageNum};
% create bit extraction group box
Children.parametersGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Bit extraction'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.parametersGroupbox);
Children.numOfBitsLabel = uicontrol( ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'text', ...
    'String',           'Number of bits:', ...
    'Position',         ctrlPos.numOfBitsLabel);
% Tag is needed for the automatic dev test
userData = struct('min', 0, 'max', 63);
Children.numOfBitsEdit = uicontrol( ...
    'Tag',              'numOfBitsEdit', ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'edit', ...
    'BackgroundColor',  'w', ...
    'String',           '8', ...
    'Position',         ctrlPos.numOfBitsEdit, ...
    'UserData',         userData, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''numOfBitsEdit'')',pageName));
% Tag is needed for the automatic dev test
Children.numOfBitsEditButtonDown = uicontrol( ...
    'Tag',              'numOfBitsEditButtonDown', ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'pushbutton', ...
    'String',           '-', ...
    'Position',         ctrlPos.numOfBitsEditButtonDown, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''numOfBitsEditButtonDown'')',pageName));
% Tag is needed for the automatic dev test
Children.numOfBitsEditButtonUp = uicontrol( ...
    'Tag',              'numOfBitsEditButtonUp', ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'pushbutton', ...
    'String',           '+', ...
    'Position',         ctrlPos.numOfBitsEditButtonUp, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''numOfBitsEditButtonUp'')',pageName));
Children.bitidxrangeLabel = uicontrol( ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'text', ...
    'String',           'Bit range:', ...
    'Position',         ctrlPos.bitidxrangeLabel);
% Tag is needed for the automatic dev test
userData = struct('min', 0, 'max', 63);
Children.bitidxrangeEdit = uicontrol( ...
    'Tag',              'bitidxrangeEdit', ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'edit', ...
    'BackgroundColor',  'w', ...
    'String',           '[0 7]', ...
    'Position',         ctrlPos.bitidxrangeEdit, ...
    'UserData',         userData, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''bitidxrangeEdit'')',pageName));

Children.bitstoextractLabel = uicontrol( ...
    'Parent',           Children.parametersGroupbox, ...
    'Style',            'text', ...
    'String',           'Bits to extract:', ...
    'Position',         ctrlPos.bitstoextractLabel);

% get string for popup menu
enums =  tl_manage_blockset('GetEnums');
l = enums(strcmp({enums.name},'BitsToExtractEnum'));
popupString = l.strings;
% Tag is needed for the automatic dev test
Children.bitstoextractPopup = uicontrol( ...
    'Tag',              'bitstoextractPopup', ...
    'Parent',           Children.parametersGroupbox, ...
    'BackgroundColor',  'w', ...
    'Style',            'popup', ...
    'String',           popupString, ...
    'Position',         ctrlPos.bitstoextractPopup, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''bitstoextractPopup'')',pageName));
dlgdata.pageData{pageNum}.children = Children;

% create standard variable controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);
% modify panel title
set(dlgdata.pageData{pageNum}.children.tlcgoptGroupbox, 'Title', 'Output');


%-----------------------------------------------------------------------------------------
% FcnManageOutputControls manages control actions of output page
%
% INPUT ARGUMENTS
%   pageNum         number of current page
%   dlgfig          handle for dialog figure
%   dlgdata         dialog data
%   pageAction      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageOutputControls(pageNum,dlgfig,dlgdata,action)
Children = dlgdata.pageData{pageNum}.children;
switch action
    case {'numOfBitsEdit', 'numOfBitsEditButtonUp', 'numOfBitsEditButtonDown'}
        % checks for other kind of wrong parameters is implemented in
        % function 'tl_handle_editupdown'.
        [numbits, bModified] = tl_handle_editupdown( 'manage', ...
            dlgdata.data.numbits, ...
            [Children.numOfBitsEdit, Children.numOfBitsEditButtonUp, ...
            Children.numOfBitsEditButtonDown], Children.(action));
        if bModified
            dlgdata.data.numbits = num2str(numbits);
        end
    case 'bitstoextractPopup'
        dlgdata.data.bitstoextract = get(Children.bitstoextractPopup, 'Value');
        bModified = 1;
    case 'bitidxrangeEdit'
        bitidxrangeStr = strtrim(get(Children.bitidxrangeEdit,'String'));
        % check for valid entries:
        % - string has have syntax '[<number1> <number1>]
        % - <number1> has to be <= <number2>
        
        % extract range from brackets
        rangeTokens = regexp(bitidxrangeStr, '^.*\[(?<range>.*)\].*', 'names');
        if ~isempty(rangeTokens)
            range = rangeTokens.range;
        else
            % if there where no []-brackets rangeTokens is empty->next try
            range = bitidxrangeStr;
        end
        % try to get the range
        rangeNum = str2num(range); %#ok<ST2NM>
        if ~isequalwithequalnans(rangeNum, NaN) && ...
                (size(rangeNum,2) == 1 || size(rangeNum,2) == 2)
            % input is valid
            if size(rangeNum,2) == 1
                % only one number
                rangeBegin = round(real(rangeNum(1)));
                rangeEnd   = rangeBegin;
            else
                % two numbers
                rangeBegin = round(real(rangeNum(1)));
                rangeEnd   = round(real(rangeNum(2)));
                if rangeBegin > rangeEnd
                    % swap values
                    tmpNum = rangeBegin;
                    rangeBegin = rangeEnd;
                    rangeEnd = tmpNum;
                end
            end
            userData = get(Children.bitidxrangeEdit, 'UserData');
            if rangeBegin >= userData.min && rangeEnd <= userData.max
                dlgdata.data.bitidxrange = sprintf('[%i %i]', rangeBegin, rangeEnd);
            end
        else
            % input isn't valid. just use it (it will  be colored red in
            % the update function
            dlgdata.data.bitidxrange = get(Children.bitidxrangeEdit,'String');
        end
        bModified = true;

    otherwise 
        [dlgdata, bModified1] = TLManageVariableCtrls( ...
                        'manage', pageNum, dlgfig, dlgdata, action, 'output');
        [dlgdata, bModified2] = TLManageScalingCtrls( ...
                        'manage',pageNum,dlgfig,dlgdata,action,'output');
        bModified = bModified1 || bModified2;
end

%-----------------------------------------------------------------------------------------
% FcnUpdateOutputControls updates output controls
%
% INPUT ARGUMENTS
%   dlgfig          figure handle of dialog
%   dlgdata         dialog data
%   pageNum         page Number
%
% OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputControls(dlgfig, dlgdata, pageNum)

Children = dlgdata.pageData{pageNum}.children;

% update all controls
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'output');
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'output', []);

% bitstoextractPopup
set(Children.bitstoextractPopup, 'Value', dlgdata.data.bitstoextract);

% numofbitsEdit, up and down button
states.edit = 'off';
states.up   = 'off';
states.down = 'off';
states.isValid = true;
if dlgdata.data.bitstoextract == 3 || dlgdata.data.bitstoextract == 4
    states = tl_handle_editupdown('update', dlgdata.data.numbits, ...
                                            dlgdata, pageNum, 'numOfBitsEdit');
end

% bit index edit
userData = get(Children.numOfBitsEdit, 'UserData');
userData.ctrlStatus = struct('enable', states.edit, 'string', dlgdata.data.numbits);
if ~states.isValid
    % wrong input (maybe inserted outside the dialog) -> color text red
    userData.ctrlStatus.iserror = true;
end
set(Children.numOfBitsEdit, 'UserData', userData);

% up button
userData = get(Children.numOfBitsEditButtonUp, 'UserData');
userData.ctrlStatus = struct('enable', states.up);
set(Children.numOfBitsEditButtonUp, 'UserData', userData);

% down button
userData = get(Children.numOfBitsEditButtonDown, 'UserData');
userData.ctrlStatus = struct('enable', states.down);
set(Children.numOfBitsEditButtonDown, 'UserData', userData);

% bitidxrange
if dlgdata.data.bitstoextract == 5
    bitRangeEnable = 'on';
else
    bitRangeEnable = 'off';
end
% bitidxrangeEdit
userData = get(Children.bitidxrangeEdit, 'UserData');
userData.ctrlStatus = struct('enable', bitRangeEnable, ...
                                'string', dlgdata.data.bitidxrange);
% try to extract range-start and end to validate them
rangeStr = regexp(dlgdata.data.bitidxrange, '^\[(?<start>\d+) (?<end>\d+)\]$', 'names');
if isempty(rangeStr)
    userData.ctrlStatus.iserror = true;
else 
    rangeStart = str2num(rangeStr.start); %#ok<ST2NM>
    rangeEnd   = str2num(rangeStr.end); %#ok<ST2NM>
    if isequalwithequalnans(rangeStart, NaN) || ...
            isequalwithequalnans(rangeEnd, NaN) || ...
            rangeStart > rangeEnd || ...
            rangeStart < userData.min || rangeEnd > userData.max
        % beginning or end of Range are no numbers or
        % beginning is greater than the end or
        % the range is out of bounds
        userData.ctrlStatus.iserror = true;
    end
end
                            
set(Children.bitidxrangeEdit, 'UserData', userData);

% set controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

numOfBitControls = { 'numOfBitsEdit', 'numOfBitsEditButtonUp', ...
                            'numOfBitsEditButtonDown', 'bitidxrangeEdit'};
TLSetCtrlsStatus(dlgfig, Children, numOfBitControls);